package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import com.netflix.discovery.converters.Auto;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class OrderTccActionImpl implements OrderTccAction {
    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        orderMapper.create(new Order(orderId,userId,productId,count,money,0));//状态0是冻结状态
        //第一阶段成功，保存一阶段的成功标记，用来控制幂等性
        ResultHolder.setResult(getClass(), ctx.getXid(), "p");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext ctx) {
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            //标记不存在则不执行提交
            return true;
        }

        String s = ctx.getActionContext("orderId").toString();
        Long orderId = Long.valueOf(s);
        orderMapper.updateStatus(orderId,1);
        //提交成功时，删除标记
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;

    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(getClass(), ctx.getXid()) == null) {
            //标记不存在则不执行提交
            return true;
        }
        String s = ctx.getActionContext("orderId").toString();
        Long orderId = Long.valueOf(s);
        orderMapper.deleteById(orderId);
        //提交成功时，删除标记
        ResultHolder.removeResult(getClass(), ctx.getXid());
        return true;
    }


}
